package cn.itcast.dao.impl;

import cn.itcast.dao.FoodTypeDao;
import cn.itcast.entity.FoodType;
import cn.itcast.utils.JdbcUtil;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class FoodTypeDaoImpl implements FoodTypeDao {
	public void add(FoodType ft) {
		String sql = "INSERT INTO foodType(typeName) VALUES(?)";
		try {
			JdbcUtil.getQueryRunner().update(sql, ft.getTypeName());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void update(FoodType ft) {
		String sql = "update foodType set typeName=? where id=?";
		try {
			JdbcUtil.getQueryRunner().update(
					sql,
					new Object[] { ft.getTypeName(),
							Integer.valueOf(ft.getId()) });
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<FoodType> getAll() {
		String sql = "select * from foodType";
		try {
			return (List) JdbcUtil.getQueryRunner().query(sql,
					new BeanListHandler(FoodType.class));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<FoodType> getAll(String typeName) {
		String sql = "SELECT * FROM foodType WHERE typeName LIKE ?";
		try {
			return (List) JdbcUtil.getQueryRunner().query(sql,
					new BeanListHandler(FoodType.class),
					new Object[] { "%" + typeName + "%" });
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public FoodType findById(int id) {
		String sql = "select * from foodType where id=?";
		try {
			return (FoodType) JdbcUtil.getQueryRunner().query(sql,
					new BeanHandler(FoodType.class),
					new Object[] { Integer.valueOf(id) });
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(int id) {
		String sql = "delete from foodType where id = ?";
		try {
			JdbcUtil.getQueryRunner().update(sql, Integer.valueOf(id));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}